package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.dto.LikedTimesDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.LikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.tianji.remark.constants.RedisConstants;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author 蒼飞
 * @since 2023-09-12
 */
@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements LikedRecordService {
    private final RabbitMqHelper mqHelper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void addLikeRecord(LikeRecordFormDTO recordDTO) {
        // 1.基于前端的参数，判断是执行点赞还是取消点赞
        boolean success = recordDTO.getLiked() ? like(recordDTO) : unlike(recordDTO);
        // 2.判断是否执行成功，如果失败，则直接结束
        if (!success) {
            return;
        }
        // 3.如果执行成功，统计点赞总数
        Long likedTimes = redisTemplate.opsForSet()
                .size(RedisConstants.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId());
        if (likedTimes == null) {
            return;
        }
        // 4.缓存点赞总数到Redis
        redisTemplate.opsForZSet().add(
                RedisConstants.LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType(),
                recordDTO.getBizId().toString(),
                likedTimes
        );
    }

    private boolean unlike(LikeRecordFormDTO recordDTO) {
        Long userId = UserContext.getUser();
        String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId();
        Long remove = redisTemplate.opsForSet().remove(key,userId.toString());
        return remove != null && remove > 0;
//        return remove(new QueryWrapper<LikedRecord>().lambda()
//                .eq(LikedRecord::getUserId, UserContext.getUser())
//                .eq(LikedRecord::getBizId, recordDTO.getBizId()));
    }

    private boolean like(LikeRecordFormDTO recordDTO) {
        Long userId = UserContext.getUser();
        String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId();
        Long add = redisTemplate.opsForSet().add(key, userId.toString());
        return add != null && add >0;
//        // 1.查询点赞记录
//        Integer count = lambdaQuery()
//                .eq(LikedRecord::getUserId, userId)
//                .eq(LikedRecord::getBizId, recordDTO.getBizId())
//                .count();
//        // 2.判断是否存在，如果已经存在，直接结束
//        if (count > 0) {
//            return false;
//        }
//        // 3.如果不存在，直接新增
//        LikedRecord r = new LikedRecord();
//        r.setUserId(userId);
//        r.setBizId(recordDTO.getBizId());
//        r.setBizType(recordDTO.getBizType());
//        save(r);
//        return true;
    }

    /**
     * 批量查询点赞状态
     * @param bizIds
     * @return
     */

    @Override
    public List<Long> isBizLiked(List<Long> bizIds) {
        // 1.获取登录用户id
        Long userId = UserContext.getUser();
        // 2.查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        // 3.返回结果
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toList());// 收集

        //        // 1.获取登录用户id
        //        Long userId = UserContext.getUser();
        //        // 2.查询点赞状态
        //        List<LikedRecord> list = this.lambdaQuery()
        //            .in(LikedRecord::getBizId, bizIds)
        //            .eq(LikedRecord::getUserId, userId)
        //            .list();
        //        // 3.返回结果
        //        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toList());
    }

    /**
     * 根据业务id查询点赞状态
     * @param bizId
     * @return
     */
    @Override
    public Long isBizLikedOne(Long bizId) {
        String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + bizId;
        return Long.valueOf(Objects.requireNonNull(redisTemplate.opsForValue().get(key)));
//        Long userId = UserContext.getUser();
////        redisTemplate.opsForSet().
//        List<LikedRecord> list = this.lambdaQuery()
//                .eq(LikedRecord::getBizId, bizId)
//                .eq(LikedRecord::getUserId, userId)
//                .list();
//        return list.get(0).getBizId();
    }

    /**
     * 定时任务 将点赞通过mq通知服务
     * @param bizType
     * @param maxSize
     */
    @Override
    public void readLikedTimesAndSendMessage(String bizType, Integer maxSize) {
        Long userId = UserContext.getUser();


//        LikedTimesDTO likedTimesDTO = new LikedTimesDTO();
//        likedTimesDTO.setBizId(recordDTO.getBizId());
//        likedTimesDTO.setLikedTimes(likedTimes);
//        mqHelper.send(
//                LIKE_RECORD_EXCHANGE,
//                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, recordDTO.getBizType()),
//                likedTimesDTO);
    }
}
